package com.example.concurrent;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author houyangfan
 * @version 1.0
 * @date 2022/10/4 17:49
 * <p>
 * 线程之间的的通信
 */
public class ProductConsumer {
    public static void main(String[] args) {
        Data data = new Data();
        Thread thread1 = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                data.a();
            }
        }, "A");

        Thread thread2 = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                data.b();
            }
        }, "B");

        Thread thread3 = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                data.c();
            }
        }, "C");

        thread1.start();
        thread2.start();
        thread3.start();
    }
}

class Data {
    private int number = 1;
    Lock lock = new ReentrantLock();
    Condition condition1 = lock.newCondition();
    Condition condition2 = lock.newCondition();
    Condition condition3 = lock.newCondition();


    /**
     * 使用 condition 实现精准的通知和唤醒线程
     * 实现A执行完 B执行 然后C执行
     * number 1：A执行 2：B 3：C
     *
     */

    public void a(){
        try {
            lock.lock();
            while (number != 1){
                condition1.await();
            }
            System.out.println(Thread.currentThread().getName() +"--->"+ "aaaaaa");
            number = 2;
            condition2.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void b(){
        try {
            lock.lock();
            while (number != 2){
                condition2.await();
            }
            System.out.println(Thread.currentThread().getName() +"--->"+ "bbbbbbb");
            number = 3;
            condition3.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void c(){
        try {
            lock.lock();
            while (number != 3){
                condition3.await();
            }
            System.out.println(Thread.currentThread().getName() +"--->"+ "ccccccccc");
            number = 1;
            condition1.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
